package com.shuiqinling.ww.android.Util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;

public class Utils {
	public static String generateHash(String source, String hashType) {
		StringBuilder sb = new StringBuilder();
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance(hashType);
			md5.update(source.getBytes());
			for (byte b : md5.digest()) {
				sb.append(String.format("%02X", b)); // 10进制转16进制，X
														// 表示以十六进制形式输出，02
														// 表示不足两位前面补0输出
			}
			return sb.toString().toLowerCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static HashMap<String, String> parseParamStr(String paramStr) {
		String[] params = paramStr.split(";");
		HashMap<String, String> paramMap = new HashMap<String, String>();

		for (int i = 0; i < params.length; i++) {
			String param = params[i];
			String key = param.substring(0, param.indexOf("="));
			String value = param.substring(param.indexOf("=") + 1);
			paramMap.put(key, value);
		}
		return paramMap;
	}

	public static int getValueFromParamStr(String paramStr, String keyToFind) {
		int channelID = -1;

		String[] params = paramStr.split(";");
		for (int i = 0; i < params.length; i++) {
			if (params[i].startsWith(keyToFind)) {
				channelID = Integer.parseInt(params[i].substring(params[i].indexOf("=") + 1));
			}
		}
		return channelID;
	}

	public static void goURL(Activity currentActivity, String url) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setData(Uri.parse(url));
		currentActivity.startActivity(intent);
	}

	public static boolean isPackageAvilible(Context context, String packageName) {

		final PackageManager packageManager = context.getPackageManager();

		// 获取所有已安装程序的包信息
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
		for (int i = 0; i < pinfo.size(); i++) {

			// 循环判断是否存在指定包名
			if (pinfo.get(i).packageName.equalsIgnoreCase(packageName)) {
				return true;
			}

		}
		return false;
	}
}
